<?php
/**
 * User: May
 * Date: 2018/6/8
 * Time: 22:01
 */

namespace app\index\controller;


use think\captcha\Captcha;

use think\Request;
use think\Session;
use \app\index\model\User as UserModel;

class User extends Base
{
    //登陆界面
    public function login()
    {
        $this->alreadyLogin();//防止重复登录
        return $this->fetch();
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    //验证登陆 $this
    public function checkLogin(Request $request)
    {
        $status = 0;
        $result = '';
        $data = $request->param();
        $rule = [
            'name|用户名' => 'require',
            'password|密码' => 'require',
            'verify|验证码' => 'require|captcha'
        ];
        //自定义验证失败信息
        $msg = [
            'name' => ['require' => '用户名不能为空，请检查'],
            'password' => ['require' => '密码不能为空，请检查'],
            'verify' => [
                'require' => '验证码不能为空，请检查',
                'captcha' => '验证码错误'
            ],
        ];
        //进行验证
        $result = $this->validate($data, $rule, $msg);
        //验证结果
        if ($result === true) {
            $map = [
                'name' => $data['name'],
                'password' => md5($data['password']),
            ];

            $user = UserModel::get($map);
            if ($user == null) {
                $result = '账号或密码错误';
            } else {
                $status = 1;
                $result = '验证通过';
                //设置用户登陆信息 session
                Session::set('user_id', $user->id);
                Session::set('user_info', $user->getData());
                //更新用户登陆次数
                $user->setInc("login_count");
            }
        }
        return ['status' => $status, 'message' => $result, 'data' => $data];
    }

    //验证码
//    public function showCaptcha()
//    {
//        $config = [
//            //验证码高度
//            'imageH' => 40,
//            //验证码宽度
//            'imageW' => 100,
//            //字体大小
//            'fontSize' => 14,
//            //字符数
//            'length' => 4,
//        ];
//        $captcha = new Captcha($config);
//        return $captcha->entry();
//    }

    //退出
    public function logout()
    {
        //退出前更新登陆时间
        UserModel::update(['login_time' => time()], ['id' => Session::get('user_id')]);
        Session::delete('user_id');
        Session::delete('user_info');
        $this->success('正在注销', 'user/login', '', '1');
//        return $this->fetch('login');
    }

    //管理员列表

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function adminList()
    {
        $this->assign('title', '管理员列表');
        $this->assign('keywords', '个人学习');
        $this->assign('desc', '案例');
        $this->view->count = UserModel::count();
        //判断当前是不是admin用户
        $userName = Session::get('user_info.name');
        if ($userName == 'admin') {
            $list = UserModel::all();
        } else {
            $list = UserModel::all(['name' => $userName]);

        }
        $this->assign('list', $list);
        return $this->fetch('admin_list');
    }

    //增加管理员
    public function adminAdd()
    {
        $this->view->assign('title', '添加管理员');
        $this->view->assign('keywords', 'php.cn');
        $this->view->assign('desc', 'PHP中文网ThinkPHP5开发实战课程');
        return $this->fetch('admin_add');
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \think\exception\DbException
     */
    //检查用户名是否可用
    public function checkUserName(Request $request)
    {
        $userName = trim($request->param('name'));
        $status = 1;
        $message = '用户名可用';
        if (UserModel::get(['name' => $userName])) {
            $status = 0;
            $message = '用户名重复，请重新输入';
        }
        return ['status' => $status, 'message' => $message];
    }

    //添加操作
    public function addUser(Request $request)
    {
        $data = $request->param();
        $status = 1;
        $message = '添加成功';
        $rule = [
            'name|用户名' => 'require|min:3|max:10',
            'password|密码' => 'require|min:3|max:10',
            'email|邮箱' => 'require|email'
        ];
        $result = $this->validate($data, $rule);
        if ($result === true) {
            UserModel::create($data);
        } else {
            $status = 0;
            $message = $result;
        }
        return ['status' => $status, 'message' => $message];
    }

    //删除用户
    public function deleteUser(Request $request)
    {
        $id = $request->param('id');
        if ($id != null) {
            UserModel::update(['is_delete' => 1], ['id' => $id]);
            UserModel::destroy($id);
        }
    }

    //编辑用户
    public function adminEdit(Request $request)
    {
        $id = $request->param('id');
        $user_info = UserModel::get($id);
        $this->view->assign('title', '编辑');
        $this->view->assign('keywords', '编辑');
        $this->view->assign('desc', '编辑用户');
        $this->assign('user_info', $user_info);
        return $this->fetch('admin_edit');
    }

    //更新用户
    public function editUser(Request $request)
    {
        $param = $request->param();
        //去掉空字符串
        foreach ($param as $key => $value) {
            if ($value != '') {
                $data[$key] = $value;
            }
        }
        $id = ['id' => $data['id']];
        $result = UserModel::update($data, $id);
        //如果是admin用户则更新角色
        if (Session::get('name') == 'admin') {
            Session::set('user_info.role', $data['role']);
        }
        if ($result == true) {
            return ['status' => 1, 'message' => '更新成功'];
        } else {
            return ['status' => 0, 'message' => '更新失败'];
        }
    }

    //更改状态
    public function setStatus(Request $request)
    {
        $id = $request->param('id');
        if (UserModel::get($id)->getData('status') == 1) {
            dump(UserModel::get($id)->getData('status'));
            UserModel::update(['status' => 0], ['id' => $id]);
        } else {
            UserModel::update(['status' => 1], ['id' => $id]);
        }
    }
}
